package com.zxl.register.server.socket;

import com.zxl.register.base.Result;
import com.zxl.register.base.business.BusinessFun;
import com.zxl.register.util.JsonUtil;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.StandardCharsets;

/**
 * socket管理
 */
public class SocketManager {


    public static void send(Result msg, AsynchronousSocketChannel socket) {
        // 发送数据到client
        if (msg != null) {
            byte[] conetent = JsonUtil.gson.toJson(msg).getBytes();
            send(conetent, socket);
        }
    }


    public static void send(String msg, AsynchronousSocketChannel socket) {

        // 发送数据到client
        if (!StringUtils.isEmpty(msg)) {
            byte[] conetent = msg.getBytes();
            send(conetent, socket);
        }
    }

    public static void send(byte[] msg, AsynchronousSocketChannel socket) {

        // 发送数据到client
        ByteBuffer readBuffer = ByteBuffer.wrap(msg);
        socket.write(readBuffer, readBuffer, new CompletionHandler<Integer, ByteBuffer>() {
            @Override
            public void completed(Integer result, ByteBuffer attachment) {
                try {
                    System.out.println("msg send finish ！socket: " + socket.getRemoteAddress().toString());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void failed(Throwable exc, ByteBuffer attachment) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

    }




    public static void read(AsynchronousSocketChannel socketChannel, BusinessFun businessFun) throws IOException {
        String addr=socketChannel.getRemoteAddress().toString();
        ByteBuffer readBuffer=ByteBuffer.allocate(1024);
        System.out.println("received from  socket: "+addr);
        socketChannel.read(readBuffer, readBuffer, new CompletionHandler<Integer, ByteBuffer>() {
            @Override
            public void completed(Integer result, ByteBuffer attachment) {
                attachment.flip();
                byte[] body = new byte[attachment.remaining()];
                attachment.get(body);
                String content=new String(body, StandardCharsets.UTF_8);
                System.out.println(" receive : "+content);
                if(businessFun!=null){
                    businessFun.doSomeThing(socketChannel,content);
                }
                try {
                    read(socketChannel,null);
                } catch (IOException e) {
                    e.printStackTrace();
                }


//                Event event=null;
//                try {
//                    event= JsonUtil.gson.fromJson(content,Event.class);
//                } catch (Exception e) {
//                    System.out.println(" process read msg happen exception ! socket : "+addr);
//                    return;
//                }
//                ServiceInstance serviceInstance=event.getInstance();
//                if(serviceInstance==null){
//                    serviceInstance=new ServiceInstance();
//                }
//                serviceInstance.setAddress(addr);
//                serviceInstance.setLastHeartBeat(System.currentTimeMillis());
//                serviceInstance.setSocketChannel(socketChannel);
//                event.setReceivedTime(System.currentTimeMillis());
//                EventPool.push(event);
            }

            @Override
            public void failed(Throwable exc, ByteBuffer attachment) {
                try {
                    socketChannel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    public static byte[] intToByteArray(int i) {
        byte[] result = new byte[4];
        result[0] = (byte)((i >> 24) & 0xFF);
        result[1] = (byte)((i >> 16) & 0xFF);
        result[2] = (byte)((i >> 8) & 0xFF);
        result[3] = (byte)(i & 0xFF);
        return result;
    }

}
